<template>
    <el-dialog
            title="数据空间化"
            :visible.sync="spatialVisible"
            :close-on-click-modal="false"
            width="88%"
            top="2%"
            v-dialogDrag
            v-loading="loading"
            style="margin-top: 1px"
    id="spatialDialog">
        <el-steps :active="active" finish-status="success" style="margin-top: 15px">
            <el-step title="步骤 1" icon="el-icon-edit"></el-step>
            <el-step title="步骤 2" icon="el-icon-edit"></el-step>
            <!--<el-step title="步骤 3" icon="el-icon-upload"></el-step>-->
        </el-steps>
        <div v-show="step1" style="margin-top: 8%;margin-left: 30%;height:350px">
            <el-row class="step">
                <span style="font-size: 20px;">请填写文件名称：</span>
                <el-input v-model="fileNewName" clearable style="margin-left: 5%;width: 50%"
                          placeholder="请输入内容"></el-input>
            </el-row>
            <el-row class="step">
                <span style="font-size:20px;">请填写文件描述：</span>
                <el-input v-model="fileDescription" clearable style="margin-left: 5%;width: 50%"
                          placeholder="请输入内容"></el-input>
            </el-row>
            <el-row class="step">
                <span style="font-size: 20px;">请选择图层类型：</span>
                <el-select v-model="value" placeholder="请选择" style="margin-left: 5%;width: 50%">
                    <el-option
                            v-for="item in picOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-row>
            <el-row class="step">
                <span style="font-size:20px;">请填写坐标系：</span>
                <el-input v-model="fileCors" clearable style="margin-left: 7.5%;width: 50%"
                          placeholder="请填写坐标系"></el-input>
            </el-row>
        </div>
        <div v-show="step2" style="margin-top: 3%;height:350px">
            <el-checkbox v-show="checkShow" v-model="head" @change="judgeHead" style="margin-bottom: 20px">数据没有表头</el-checkbox>
            <el-table :data="fieldTableData"
                      style="width: 100%;background: #ffffff;"
                      empty-text=" "
                      stripe border
                      highlight-current-row
                      max-height="300px"
                      @selection-change="handleSelectionChange">
                <el-table-column
                        type="selection"
                        label=""
                        width="30"
                        align="center">
                </el-table-column>
                <el-table-column
                        v-if="this.head === false"
                        prop="oldName"
                        label="源字段"
                        width="fit-content"
                        min-width="50">
                </el-table-column>
                <el-table-column
                        v-if="this.head === true"
                        prop="noHead"
                        label="源字段"
                        width="fit-content"
                        min-width="50">
                </el-table-column>
                <!--有默认值-->
                <el-table-column
                        label="目标字段"
                        min-width="60"
                        width="fit-content"
                        align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.name" clearable placeholder="请输入内容"
                                  :disabled="scope.row.rowDisabled"></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                        label="目标字段中文名称"
                        min-width="100"
                        width="fit-content"
                        align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.text" clearable placeholder="请输入内容"
                                  :disabled="scope.row.rowDisabled"></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                        label="字段描述"
                        min-width="100"
                        width="120"
                        align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.description" clearable placeholder="请输入内容"
                                  :disabled="scope.row.rowDisabled"></el-input>
                    </template>
                </el-table-column>
                <!--可选择-->
                <el-table-column
                        label="类型"
                        min-width="60"
                        width="120"
                        align="center">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.type" placeholder="请选择" :disabled="scope.row.rowDisabled">
                            <el-option
                                    v-for="item in typeOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <!--填写-->
                <el-table-column
                        label="长度"
                        min-width="80"
                        width="fit-content"
                        align="center">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.length" controls-position="right" :min="1"
                                         :max="255" :disabled="scope.row.rowDisabled"></el-input-number>
                    </template>
                </el-table-column>
                <!--checkBox-->
                <el-table-column
                        label="主键"
                        width="50"
                        align="center">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.isKey" :disabled="scope.row.keyDisabled"
                                     @change="judgeKey"></el-checkbox>
                        <!--<el-checkbox v-model="scope.row.isKey" :disabled="scope.row.keyDisabled"-->
                        <!--@change="judgeKey"></el-checkbox>-->
                    </template>
                </el-table-column>
                <el-table-column
                v-if="this.path.indexOf('.shp') ==-1 && this.ifHasGeometry"
                        label="空间字段"
                        width="80"
                        align="center">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.isGeometry" :disabled="scope.row.geometryDisabled"
                                     @change="judgeGeometry(scope.row)"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column
                        label="时间字段"
                        width="80"
                        align="center">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.isTime" :disabled="scope.row.timeDisabled"
                                     @change="judgeTime(scope.row)"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column
                        label="中文字段"
                        width="80"
                        align="center">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.isChinese" :disabled="scope.row.rowDisabled"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column
                        label="格式"
                        width="110"
                        align="center">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.format"
                                   :disabled="scope.row.isTime === false && scope.row.isGeometry === false"
                                   placeholder="请选择">
                            <el-option
                                    v-if="scope.row.isTime === true"
                                    v-for="item in timeOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                            <el-option
                                    v-if="scope.row.isGeometry === true "
                                    v-for="item in spatialOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!--<div v-show="step3" style="width:50%;margin-left:25%;margin-top: 5%;margin-bottom: 6%">-->
        <!--<el-progress :text-inside="true" :stroke-width="24" :percentage="this.percentage"-->
        <!--:status="this.processStatus"></el-progress>-->
        <!--</div>-->
        <span slot="footer" class="dialog-footer">
            <el-button v-if="this.active===1" style="margin-top: 12px;" @click="previous">上一步</el-button>
            <el-button v-if="this.active==0" :disableds="this.dataCheck" tyle="margin-top: 12px;"
                       @click="next">下一步</el-button>
             <el-button v-if="this.active===1" :disableds="this.dataCheck" tyle="margin-top: 12px;"
                        @click="confirm">确定</el-button>
            <!--<el-button v-if="this.active === 2 " style="margin-top: 12px;"-->
            <!--@click="confirm">确  定</el-button>-->
            <!--<el-button @click="cancel">取 消</el-button>-->
        </span>
    </el-dialog>

</template>

<script>

    export default {
        name: "spatialDialog",
        // props: ['loaderTableData'],
        data() {
            return {
                checkShow:false,
                multipleSelection: [],
                active: 0,
                spatialVisible: false,
                radio: '0',
                step1: true,
                step2: false,
                //step3: false,
                fileCors:'',
                fileDescription: '',
                chooseTypeValue: '',
                primaryKeyChecked: false,
                fileNewName: '',
                fieldTableData: [],
                chooseField: [],
                typeOptions: [{
                    value: 'String',
                    label: 'String'
                }, {
                    value: 'Integer',
                    label: 'Integer'
                }, {
                    value: 'Float',
                    label: 'Float'
                }
                    , {
                        value: 'Long',
                        label: 'Long'
                    }
                    , {
                        value: 'Double',
                        label: 'Double'
                    }
                    , {
                        value: 'Boolean',
                        label: 'Boolean'
                    }
                    , {
                        value: 'Date',
                        label: 'Date'
                    }],
                spatialType: '',
                timeType: '',
                timeOptions: [{
                    value: 'HH:mm:ss',
                    label: 'HH:mm:ss'
                }, {
                    value: 'yyyy/MM/dd',
                    label: 'yyyy/MM/dd'
                }, {
                    value: 'yyyy-MM-dd',
                    label: 'yyyy-MM-dd'
                }, {
                    value: 'yyyy/MM/dd HH:mm:ss',
                    label: 'yyyy/MM/dd HH:mm:ss'
                }, {
                    value: 'yyyy-MM-dd HH:mm:ss',
                    label: 'yyyy-MM-dd HH:mm:ss'
                }, {
                    value: 'yyyy年MM月dd日 HH时mm分ss秒',
                    label: 'yyyy年MM月dd日 HH时mm分ss秒'
                },
                    {
                        value: 'EEE MMM dd HH:mm:ss zzz yyy',
                        label: 'EEE MMM dd HH:mm:ss zzz yyy'
                    }],
                picOptions: [{
                    value: 'POINT',
                    label: 'POINT'
                }, {
                    value: 'POLYLINE',
                    label: 'POLYLINE'
                }, {
                    value: 'POLYGON',
                    label: 'POLYGON'
                }, {
                    value: 'TABLE',
                    label: 'TABLE'
                }],
                fieldOptions: [],
                // originTableData: [],
                value: '',
                url: '',
                spatialField: '',
                timeField: '',
                IDField: '',
                chineseField: '',
                res: {},
                timeSelection: [],
                geometrySelection: [],
                keySelection: [],
                hasGeometry: false,
                dataRes: {},
                hasHead: true,
                head: false,
                path: '',
                dataCheck: false,
                postData: {},
                postData2: {},
                key: 0,
                check: 0,
                loading: false
                // processStatus: 'success',
                // percentage: 0
            }
        },
        props: {},
        computed: {

            spatialOptions() {
                if (this.value === 'POINT') {
                    return [{
                        value: 'lon',
                        label: 'PtLon'
                    }, {
                        value: 'lat',
                        label: 'PtLat'
                    }, {
                        value: 'cors',
                        label: 'Coordinates'
                    }, {
                        value: 'wkt',
                        label: 'wkt'
                    }]
                } else if (this.value === 'ODPAIR') {
                    return [{
                        value: 'start_lon',
                        label: 'OdSLon'
                    }, {
                        value: 'start_lat',
                        label: 'OdSLat'
                    }, {
                        value: 'end_lon',
                        label: 'OdELon'
                    }, {
                        value: 'end_lat',
                        label: 'OdELat'
                    }]
                } else {
                    return [{
                        value: 'cors',
                        label: 'Coordinates'
                    }, {
                        value: 'wkt',
                        label: 'wkt'
                    }]
                }
            },
            ifHasGeometry() {
                if (this.value == 'TABLE') {
                    //把表格中的空间字段都设为false；
                    for (let aRow of this.fieldTableData) {
                        aRow.isGeometry=false;
                    }
                    return false
                } else {
                    return true
                }
            }
        },
        methods: {
            ggg(){
                if(this.path.indexOf(".csv")){
                    alert("是个csv");
                    return true;
                }
                else{
                    alert("是个shp");
                    return false;
                }
            },
            //判断数据有没有表头
            judgeHead() {
                this.hasHead = !this.head;
                if (this.hasHead === false) {
                    for (let col of this.fieldTableData) {
                        col.name = [];
                        col.text = [];
                    }
                } else {
                    for (let col of this.fieldTableData) {
                        col.name = col.oldName;
                        col.text = col.oldName;
                    }
                }
            },
            //设定唯一主键
            judgeKey(val) {
                if (val === true) {
                    this.keySelection.push(val);
                } else {
                    this.keySelection.pop();
                }
                for (let row of this.fieldTableData) {
                    if (row.isKey === true) {
                        row.keyDisabled = false;
                    } else {
                        row.keyDisabled = true;
                    }
                }
                if (this.keySelection.length === 0) {
                    for (let row of this.fieldTableData) {
                        row.keyDisabled = false;
                    }
                }
            },
            //时间字段与空间字段不重复
            judgeTime(row) {
                for (let aRow of this.fieldTableData) {
                    if (row.oldName == aRow.oldName) {
                        if (row.isTime === true) {
                            aRow.timeDisabled = false;
                            aRow.geometryDisabled = true;
                        } else {
                            aRow.timeDisabled = false;
                            aRow.geometryDisabled = false;
                        }
                    }
                }
            },
            //设定唯一空间字段，同时空间字段与时间字段不重复
            judgeGeometry(row) {
                if (row.isGeometry === true ) {
                    this.geometrySelection.push(row.isGeometry);
                } else {
                    this.geometrySelection.pop();
                }
                for (let aRow of this.fieldTableData) {
                    if (aRow.isGeometry === true) {
                        aRow.timeDisabled = true;
                        aRow.geometryDisabled = false;
                    } else {
                        aRow.timeDisabled = false;
                        aRow.geometryDisabled = true;
                    }
                }
                if (this.geometrySelection.length === 0) {
                    for (let row of this.fieldTableData) {
                        row.geometryDisabled = false;
                    }
                }
            },
            next() {
                if (this.active === 0) {
                    if (this.value === "" || this.fileNewName === '' || this.fileDescription === ''|| this.fileCors==='') {
                        this.$message({
                            message: '请正确填写参数',
                            type: 'warning'
                        });
                    } else {
                        this.active++;
                        this.step1 = false;
                        this.step2 = true;
                    }

                }
                console.log(this.active);
            },
            cancel() {
                this.spatialVisible = false;
                this.active = 0;
                this.value = '';
                this.fileNewName = '';
                this.fileDescription = '';
                this.fileCors='';
                this.step1 = true;
                this.step2 = false;
            },
            previous() {
                if (this.active === 1) {
                    this.active = 0;
                    this.step1 = true;
                    this.step2 = false;
                } else if (this.active === 2) {
                    this.active = 1;
                    this.step1 = false;
                    this.step2 = true;
                }
            },
            //确认数据并进行入库
            confirm() {
                this.createPostData();
                if (this.dataCheck) {
                    this.active++;
                    this.loading = true;
                    this.step1 = false;
                    this.step2 = false;
                    let that = this;
                    // let url = "http://localhost:9000/dbfg/spatial/create/dataset";
                    let url="";
                    if(that.path.indexOf(".csv")!== -1){
                        url=that.$URL.datasetCreateUrl;
                    }
                    if(that.path.indexOf(".shp")!== -1){

                        url=that.$URL.shpCreateUrl;
                    }
                    this.$axios.post(url, that.postData).then(function (res) {
                        if (res.code === 200) {
                            that.loading = false;
                            that.spatialVisible = false;
                            that.$router.push({
                                name: 'personalDataMonitor'
                            });
                            that.$message({
                                type: 'success',
                                message: '数据校验成功，开始入库,已前往个人数据集查看进度'
                            });
                        }
                        if (res.message.indexOf('入库') !== -1) {
                            that.processStatus = 'success';
                            let Timer = setInterval(function () {
                                if (that.percentage < 100) {
                                    that.percentage = that.percentage + 10;
                                } else {
                                    clearInterval(Timer);
                                }
                            }, 5000);
                        } else {
                            that.processStatus = 'exception';
                            that.percentage = 0;
                        }
                    }).catch(function (error) {
                        that.loading = false;
                        console.log(error);
                        that.$message.error('数据尝试入库失败!');
                    })
                }
            },
            // 创建表格数据
            handleRes(res) {
                this.dataRes = res.body;
                //初始化fieldTableData
                debugger
                this.fieldTableData = JSON.parse(res.body.fields);
                this.originTableData = JSON.parse(res.body.fields);
                for (let i = 0; i < this.originTableData.length; i++) {
                    this.fieldTableData[i].oldName = this.fieldTableData[i].name;
                    this.fieldTableData[i].noHead = i;
                    this.fieldTableData[i].oldChineseName = this.fieldTableData[i].text;
                    this.fieldTableData[i].timeDisabled = false;
                    this.fieldTableData[i].geometryDisabled = false;
                    this.fieldTableData[i].keyDisabled = false;
                    this.fieldTableData[i].rowDisabled = false;
                }
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
                //判断主键
                // 匹配选中的行
                let index = [];
                for (let data of this.multipleSelection) {
                    index.push(data.noHead)
                }
                for (let i = 0; i < index.length; i++) {
                    if (this.fieldTableData[index[i]].isKey === true) {
                        this.fieldTableData[index[i]].keyDisabled = false;
                    }
                    if (this.fieldTableData[index[i]].isTime === true) {
                        this.fieldTableData[index[i]].geometryDisabled = true;
                    }
                    if (this.fieldTableData[index[i]].isGeometry === true) {
                        this.fieldTableData[index[i]].timeDisabled = true;
                    }
                    this.fieldTableData[index[i]].rowDisabled = false;
                }
            },
            //创建需要post的数据
            createPostData() {
                if( this.path.indexOf(".csv")!== -1){
                let postData = {};
                let constructedData = {};
                postData.path = this.path;
                postData.hasHead = this.hasHead;
                constructedData.userid = "1";
                constructedData.id = this.dataRes.id;
                constructedData.size = this.dataRes.size;
                constructedData.picurl = this.dataRes.picurl;
                constructedData.createtime = this.dataRes.createtime;
                constructedData.storetype = this.dataRes.storetype;
                constructedData.lastmodifytime = this.dataRes.lastmodifytime;
                constructedData.name = this.fileNewName;
                constructedData.description = this.fileDescription;
                constructedData.isspatialdata = this.hasGeometry;
                constructedData.datatype = this.value;
                constructedData.cors=this.fileCors;
                let postField = [];
                let fieldMap = [];
                let index = [];
                for (let data of this.multipleSelection) {
                    index.push(data.noHead)
                }
                for (let i = 0; i < index.length; i++) {
                    let field = {};
                    field.name = this.fieldTableData[index[i]].name;
                    field.text = this.fieldTableData[index[i]].text;
                    field.type = this.fieldTableData[index[i]].type;
                    field.length = this.fieldTableData[index[i]].length;
                    field.description = this.fieldTableData[index[i]].description;
                    field.isKey = this.fieldTableData[index[i]].isKey;
                    field.isGeometry = this.fieldTableData[index[i]].isGeometry;
                    field.isTime = this.fieldTableData[index[i]].isTime;
                    field.format = this.fieldTableData[index[i]].format;
                    field.isChinese = this.fieldTableData[index[i]].isChinese;
                    field.index=index[i];
                    postField.push(field);
                    let map = {};
                    if (this.hasHead === true) {
                        map.target = this.fieldTableData[index[i]].oldName;
                    } else {
                        map.target = this.fieldTableData[index[i]].noHead;
                    }
                    map.source = this.fieldTableData[index[i]].name;
                    fieldMap.push(map);
                }

                // constructedData.fields = JSON.stringify(postField);
                constructedData.fields = postField;
                postData.fieldsMap = fieldMap;
                postData.constructedData = constructedData;
                console.log(postData);
                this.checkData(postField);
                this.postData = postData;
                }
                else{
                    let postData = {};
                    let constructedData = {};
                    postData.path = this.path;
                    postData.hasHead = this.hasHead;
                    constructedData.userid = "1";
                    constructedData.id = this.dataRes.id;
                    constructedData.size = this.dataRes.size;
                    constructedData.picurl = this.dataRes.picurl;
                    constructedData.createtime = this.dataRes.createtime;
                    constructedData.storetype = this.dataRes.storetype;
                    constructedData.lastmodifytime = this.dataRes.lastmodifytime;
                    constructedData.name = this.fileNewName;
                    constructedData.description = this.fileDescription;
                    constructedData.isspatialdata = this.hasGeometry;
                    constructedData.datatype = this.value;
                    // constructedData.cors=this.fileCors;
                    let postField = [];
                    let fieldMap = [];
                    let index = [];
                    for (let data of this.multipleSelection) {
                        index.push(data.noHead)
                    }
                    for (let i = 0; i < index.length; i++) {
                        let field = {};
                        field.name = this.fieldTableData[index[i]].name;
                        field.text = this.fieldTableData[index[i]].text;
                        field.type = this.fieldTableData[index[i]].type;
                        field.length = this.fieldTableData[index[i]].length;
                        field.description = this.fieldTableData[index[i]].description;
                        field.isKey = this.fieldTableData[index[i]].isKey;
                        field.isGeometry = this.fieldTableData[index[i]].isGeometry;
                        field.isTime = this.fieldTableData[index[i]].isTime;
                        field.format = this.fieldTableData[index[i]].format;
                        field.isChinese = this.fieldTableData[index[i]].isChinese;
                        postField.push(field);
                        let map = {};
                        if (this.hasHead === true) {
                            map.target = this.fieldTableData[index[i]].oldName;
                        } else {
                            map.target = this.fieldTableData[index[i]].noHead;
                        }
                        map.source = this.fieldTableData[index[i]].name;
                        fieldMap.push(map);
                    }

                    constructedData.fields = JSON.stringify(postField);
                    // constructedData.fields = postField;
                    postData.fieldsMap = fieldMap;
                    postData.constructedData = constructedData;
                    console.log(postData);
                    this.checkData(postField);
                    this.postData = postData;
                }




            },
            //检查数据是否正确
            checkData(dataF) {
                //Todo 增加检测选择od需要四个数据字段等功能
                if (dataF.length === 0) {
                    this.$message({
                        type: 'warning',
                        message: '请设置选择数据'
                    });
                    this.dataCheck = false;
                } else {
                    //OD流数据选择字段总数判断
                    if (this.value == 'ODPair') {
                        if (dataF.length < 4) {
                            this.$message({
                                type: 'warning',
                                message: '请至少选择4个数据'
                            });
                            this.dataCheck = false;
                        }
                    }
                    this.key = 0;
                    this.check = 0;
                    for (let data of dataF) {
                        this.singleCheck(data);
                    }
                    if (this.key !== 1) {
                        this.$message({
                            type: 'warning',
                            message: '请设置主键'
                        });
                        this.dataCheck = false;
                    } else if (this.check !== 0) {
                        this.$message({
                            type: 'warning',
                            message: '请设置格式'
                        });
                        this.dataCheck = false;
                    } else {
                        this.dataCheck = true;
                    }
                }
            },
            //单条数据的检查
            singleCheck(data) {
                if (data.isGeometry) {
                    if (data.format === "") {
                        this.check = this.check + 1;
                    }
                }
                if (data.isKey) {
                    this.key = this.key + 1;
                }
            }
        }
        ,
        created() {
            let that = this;
            this.$Bus.$on('spatialVisible', params => {
                that.spatialVisible = params.visible;
                that.path = params.path;
                that.fileNewName=params.fileName.substring(0,params.fileName.indexOf('.'));
                // that.value='TABLE';
                //发送请求 path和hasHead 获取数据 fileTableData
                // let url = "http://localhost:9000/dbfg/spatial/get/fieldsinfo?path=" + that.path +
                //     "&hasHead=" + that.hasHead.toString();

                if(that.path.indexOf(".shp")!==-1){
                    this.$axios.get(that.$URL.shpInitUrl + that.path +
                        "&hasHead=" + that.hasHead).then(function (res) {

                        that.fileDescription=res.body.description;
                        // that.fileCors=res.body.cors;
                        that.value=res.body.datatype
                        that.handleRes(res);
                    }).catch(function (error) {
                        console.log(error)
                    })
                }
                if(that.path.indexOf(".csv") !==-1){
                    this.$axios.get(that.$URL.datasetInitUrl + that.path +
                        "&hasHead=" + that.hasHead).then(function (res) {
                        that.fileDescription=res.body.description;
                        that.fileCors=res.body.cors;
                        that.value=res.body.datatype;
                        that.checkShow=true;
                        that.handleRes(res);
                    }).catch(function (error) {
                        console.log(error)
                    })
                }
            });

        }
        ,
        mounted() {

        }
    }
</script>

<style>
    .step {
        margin: 20px
    }

    .el-input-number {
        width: 100% !important
    }
    #spatialDialog .el-dialog__body{
        overflow: hidden;
    }

</style>